<template>
  <div class="picture-container">
    <form action="#" method="post" ref="postMsgForm">
      <div class="course-title">
        <!-- 课程标题 -->
        <div class="title-msg">
          <span>帖子标题（必填）</span>
        </div>
        <el-input
          v-model="postMsg.title"
          maxlength="20"
          minlength="1"
          placeholder="请输入帖子标题..."
        ></el-input>
      </div>
      <!-- 课程封面图片 -->
      <div class="coursePicHeader">
        <div class="title-msg">
          <span>帖子封面（必填至多4张）</span>
        </div>
        <div class="upload-contaner">
          <el-upload
            :action="actionsUrl"
            :headers="headers"
            :disabled="uploadFlag"
            accept="jpg,png,jepg,image"
            list-type="picture-card"
            class="avatar-uploader"
            :limit="4"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" v-show="!uploadFlag"></i>
            <i class="el-icon-loading" v-show="uploadFlag"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </div>
      </div>
      <div class="course-introduce">
        <!-- 课程描述 -->
        <div class="title-msg">
          <span>帖子简介（必填）</span>
        </div>
        <div>
          <el-input
            type="textarea"
            :rows="4"
            :maxlength="200"
            :show-word-limit="true"
            placeholder="请输入描述...."
            v-model="postMsg.content.introduce"
          >
          </el-input>
        </div>
      </div>
      <div class="course-pics">
        <!-- 批量上传课程图片 -->
        <div class="title-msg">
          <span>请您选择其他资源</span>
        </div>
        <div class="editor-container">
          <Editor ref="quillEditor" :minHeight="600" :value="editorValue">
          </Editor>
        </div>
      </div>
      <div class="LABEL-container">
        <div class="title-msg">
          <span>请您选择分类（必填）</span>
        </div>
        <div class="category">
          <el-radio-group v-model="postMsg.NavID">
            <el-radio
              :label="item.id"
              v-for="(item, index) in navData"
              :key="index"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </div>
        <!-- <div>
          <div class="title-msg">
            <span>请您子分类</span>
          </div>
          <el-cascader :options="options" :show-all-levels="false" @change="changeValue"></el-cascader>
        </div> -->
      </div>
    </form>
    <div class="upload-btn">
      <el-button type="primary" @click="uploadPost()" class="uploadPost-btn"
        >确认提交</el-button
      >
    </div>
  </div>
</template>
<script>
import { postMsgInit, uploadImageList } from "@/utils/szptUtils/postMsgInit.js";
import { fmtOptionData, fmtTagDto } from "./fmtOptionsData";
import { saveUserPost } from "@/utils/szptUtils/saveUserPost.js";
import { getToken } from "../../../../utils/auth";
import { posTitelImg } from "@/api/szpt/postMsg.js";
import { BASE_URL } from "@/plateFormTag.js";
import { savePost } from "@/api/szpt/savePost.js";
import ThumbsUpMsgVue from "../../szptMsgPage/ThumbsUpMsg.vue";
export default {
  name: "postPictures",
  data() {
    return {
      szptUploadUrl: this.DataTag.actionsUrl.url,
      // 图片回显地址
      imageUrl: "",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 暂存封面图片数组
      fileList: [],
      // 存储线上图片url数据
      imageUrlArray: [],

      editorValue: "",
      // 单个图片上传地址(服务器)
      actionsUrl: this.DataTag.actionsUrl.url,
      // 批量图片上传地址
      picsActionUrl: this.DataTag.picsActionUrl.url,
      // 保存模块数据
      navData: [],
      // 是否暂时禁用上传按钮
      uploadFlag: false,
      // 多个图片上传所需参数
      dialogImageUrl: "",
      dialogVisible: false,
      tokenStr: getToken(),
      postMsg: {
        // 帖子标题
        title: "",
        // 帖子简介
        remark: "",
        // 帖子所属模块id
        NavID: "",
        // 所属模块名字
        NavName: "",
        //额外需要传输数据
        content: {
          //帖子封面图片
          titlePicFile: [],
          // 富文本框获取的数据
          introduce: "",
        },
      },
    };
  },
  methods: {
    // 处理上传url地址数据
    handlePicUrl(fileList) {
      if (fileList instanceof Array && fileList.length > 0) {
        fileList.forEach((item) => {
          this.postMsg.content.titlePicFile.push(item.url);
        });
      }
    },
    // 上传封面图片
    handleUploadSuccess(response, file, fileList) {
      this.uploadFlag = true;
      // 图片上传成功
      const options = {
        compressQualityFlag: true,
        saveOriginalQualityFlag: true,
        waterMarkFlag: true,
        OriginUrlPass: "",
        lowQuilUrlPass: "",
      };
      posTitelImg(file.raw, options)
        .then((resp) => {
          if (resp.code === 200 && resp.data) {
            options.OriginUrlPass =
              BASE_URL.lookThroughPicurl + resp.data.originalQualityPaths[0];
            options.lowQuilUrlPass =
              BASE_URL.lookThroughPicurl + resp.data.lowQualityPaths[0];
            //存储封面图片
            //  this.imageUrlArray.push(options.lowQuilUrlPass)
            fileList[fileList.length - 1].url = options.lowQuilUrlPass;
            this.fileList = fileList;
            this.uploadFlag = false;
          } else {
            console.log("图片不存在！");
          }
        })
        .catch((err) => {
          console.log(err + "图片上传错误");
        });
    },
    // 发布后清空数据一次
    resetData() {
      this.postMsg.title = "";
      this.postMsg.remark = "";
      (this.postMsg.NavID = ""),
        (this.postMsg.NavName = ""),
        (this.postMsg.content.titlePicFile = []),
        (this.postMsg.content.introduce = "");
    },
    //移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList.filter((item) => item !== file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadPost() {
      this.handlePicUrl(this.fileList);
      this.postMsg.remark = this.$refs.quillEditor.currentValue;
      if (
        this.postMsg.title &&
        this.postMsg.content.introduce &&
        this.postMsg.content.titlePicFile.length > 0 &&
        this.postMsg.NavID
      ) {
        this.$confirm("是否确认提交, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 提交保存信息
            let postData = fmtTagDto(this.postMsg, this.navData);
            savePost(postData).then((resp) => {
              if (resp.code === 200) {
                this.$message({ type: "success", message: "发布成功!" });
                this.$router.replace("/szptHome?id=191");
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "提交失败，已取消提交",
            });
            console.log("@@@@", postData);
          });
      } else {
        this.$message({
          showClose: true,
          message: "表单任意一项不能为空！请填写完整重试吧~",
          type: "warning",
        });
      }
    },
  },
  computed: {
    // menusList() {
    //   return this.$store.menus.menusRoutes
    // },
    // NavigatorPost() {
    //   // 发布帖子的版块
    //   return JSON.parse(window.localStorage.getItem('menusRoutes'))
    // },
    // tagList() {
    //   return JSON.parse(window.localStorage.getItem('tagList'))
    // },
    // 存储级联里面的数据
    // options() {
    //   return fmtOptionData(this.tagList)
    // },
  },
  mounted() {
    // this.resetData();
    this.getDicts("szpt_nav_status").then((response) => {
      const navData = response.data;
      navData.forEach((navItem) => {
        navItem.id = navItem.dictCode;
        navItem.name = navItem.remark;
        navItem.path = navItem.dictValue;
      });
      this.navData = navData;
    });
  },
};
</script>

<style scoped>
.picture-container {
  width: 100%;
  height: auto;
  min-height: 400px;
  padding: 20px;
}

.course-title {
  width: 100%;
  height: auto;
  line-height: 30px;
}

.title-msg {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-weight: bold;
  color: #666;
}

.coursePicHeader {
  width: 100%;
  height: auto;
  margin-top: 40px;
}

.upload-contaner {
  width: auto;
  height: auto;
  display: inline-block;
  padding: 10px;
  background-color: #eceaea;
}

.course-introduce {
  width: 100%;
  height: auto;
  margin-top: 30px;
}

.course-pics {
  margin-top: 20px;
}

.pics-container {
  width: auto;
  height: auto;
  display: inline-block;
  margin-top: 0px;
  padding: 10px;
}

.upload-btn {
  width: 100%;
  height: auto;
  margin-top: 30px;
  text-align: center;
  line-height: 30px;
}

.uploadPost-btn {
  width: 250px;
}

.category {
  width: 100%;
  height: auto;
  height: 30px;
  line-height: 30px;
  margin-top: 20px;
  margin-bottom: 20px;
}

.LABEL-container {
  width: 100%;
  height: auto;
  margin-top: 10px;
}

/**
 * 这下面封面图片上传的样式
 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
